package model;

import app.App;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class StockIn {

    private int stockInId;
    private int productId;
    private String productName;
    private float purchasePrice;
    private int count;
    private String vendor;
    private Timestamp stockInTime;
    Product product;

    public StockIn() {}

    public StockIn(int stockInId, int productId, String productName, float purchasePrice, int count, String vendor, Timestamp stockInTime, Product product) {
        this.stockInId = stockInId;
        this.productId = productId;
        this.productName = productName;
        this.purchasePrice = purchasePrice;
        this.count = count;
        this.vendor = vendor;
        this.stockInTime = stockInTime;
        this.product = product;
    }

    public int getStockInId() {
        return stockInId;
    }

    public void setStockInId(int stockInId) {
        this.stockInId = stockInId;
    }

    public int getProductId() {
        return productId;
    }

    public void setProductId(int productId) {
        this.productId = productId;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public float getPurchasePrice() {
        return purchasePrice;
    }

    public void setPurchasePrice(float purchasePrice) {
        this.purchasePrice = purchasePrice;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public String getVendor() {
        return vendor;
    }

    public void setVendor(String vendor) {
        this.vendor = vendor;
    }

    public Timestamp getStockInTime() {
        return stockInTime;
    }

    public void setStockInTime(Timestamp stockInTime) {
        this.stockInTime = stockInTime;
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public Object[] toTableObjectArray() {
        return new Object[]{stockInId, productId, productName, purchasePrice, count, vendor, stockInTime};
    }

    @Override
    public String toString() {
        return "StockIn{" +
                "stockInId=" + stockInId +
                ", productId=" + productId +
                ", productName='" + productName + '\'' +
                ", purchasePrice=" + purchasePrice +
                ", count=" + count +
                ", vendor='" + vendor + '\'' +
                ", stockInTime=" + stockInTime +
                '}';
    }

    //获取入库记录
    public static StockIn getStockInRecord(int stockInId) {
        Connection conn ;
        try {
            conn = App.dataSource.getConnection();//打开连接
            PreparedStatement ps = conn.prepareStatement("SELECT * FROM stockin WHERE `stockinid` = ?");
            ps.setObject(1, stockInId);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                StockIn stockIn = new StockIn();
                stockIn.setStockInId(rs.getInt(1));
                stockIn.setProductId(rs.getInt(2));
                stockIn.setProductName(rs.getString(3));
                stockIn.setPurchasePrice(rs.getFloat(4));
                stockIn.setCount(rs.getInt(5));
                stockIn.setVendor(rs.getString(6));
                stockIn.setStockInTime(rs.getTimestamp(7));
                conn.close();
                return stockIn;
            }
            conn.close();
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
        return null;
    }

    //获取入库列表
    public static List<StockIn> getStockInList() {
        List<StockIn> stockInList = new ArrayList<>();

        Connection conn;
        try {
            conn = App.dataSource.getConnection();//打开连接
            PreparedStatement ps = conn.prepareStatement("SELECT * FROM stockin");
            ResultSet rs = ps.executeQuery();
            while(rs.next()) {
                StockIn stockIn = new StockIn();
                stockIn.setStockInId(rs.getInt(1));
                stockIn.setProductId(rs.getInt(2));
                stockIn.setProductName(rs.getString(3));
                stockIn.setPurchasePrice(rs.getFloat(4));
                stockIn.setCount(rs.getInt(5));
                stockIn.setVendor(rs.getString(6));
                stockIn.setStockInTime(rs.getTimestamp(7));
                stockInList.add(stockIn);
                System.out.println(stockIn);
            }
            conn.close();
            return stockInList;
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
        return null;
    }

    //记录入库订单并入库商品（事务）
    public static boolean stockIn(StockIn stockIn) {
        Connection conn = null;
        try {
            conn = App.dataSource.getConnection();//打开连接
            conn.setAutoCommit(false);

            //添加/更新商品
            System.out.println("入库的信息："+stockIn);

            Product product = stockIn.getProduct();

            PreparedStatement ps_enter = conn.prepareStatement(
                    "INSERT INTO `product` (`productid`, `productname`, `category`,`purchaseprice`, `sellingprice`,  `quantity`) " +
                            "VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE quantity = quantity + ?");//不存在则插入，存在则更新数量
            ps_enter.setObject(1, product.getProductId());
            ps_enter.setObject(2, product.getProductName());
            ps_enter.setObject(3, product.getCategory());
            ps_enter.setObject(4, product.getPurchasePrice());
            ps_enter.setObject(5, product.getSellingPrice());
            ps_enter.setObject(6, product.getQuantity());
            ps_enter.setObject(7, product.getQuantity());
            ps_enter.executeUpdate();

            //记录入库订单
            PreparedStatement ps_discord = conn.prepareStatement(
                    "INSERT INTO `stockin` (`stockinid`, `productid`, `productname`, `purchaseprice`, `count`, `vendor`, `stockintime`) " +
                            "VALUES (?, ?, ?, ?, ?, ?, ?)");
            ps_discord.setObject(1, stockIn.getStockInId());
            ps_discord.setObject(2, stockIn.getProductId());
            ps_discord.setObject(3, stockIn.getProductName());
            ps_discord.setObject(4, stockIn.getPurchasePrice());
            ps_discord.setObject(5, stockIn.getCount());
            ps_discord.setObject(6, stockIn.getVendor());
            ps_discord.setObject(7, stockIn.getStockInTime());
            ps_discord.executeUpdate();

            conn.commit();
            conn.close();//关闭连接
            System.out.println("入库成功！");
            return true;
        } catch (SQLException throwable) {
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            throwable.printStackTrace();
        }
        System.out.println("入库失败！");
        return false;
    }

    //获取一个新的入库号
    public static int getNewStockInId() {
        Connection conn;
        try {
            conn = App.dataSource.getConnection();//打开连接
            PreparedStatement ps = conn.prepareStatement("SELECT MAX(stockinid) AS max FROM stockin");
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                int max = rs.getInt("max") + 1;
                conn.close();
                return max;
            }
            conn.close();
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
        return 1;
    }
}
